#! -*- coding:utf-8 -*-
import fcntl
import json
import logging
import os
import sys

from django.core.management.base import BaseCommand

from async import async_job
from common import orm
from common.cache import redis_cache
from common.lottery import LOTTERY_TYPE
from common.lottery import KEYWORD_TYPE_DCT
from common.lottery.cyclical.model import ACTIVITY_MODEL, ORDER_LOGIC
from common.lottery.cyclical.model import ORDER_MODEL
from common.lottery.cyclical.abstract.order import WinOrderApplyer
from common.utils import tz
from django.conf import settings

_LOGGER = logging.getLogger('worker')


class Command(BaseCommand):

    def apply(self, key, term):
        activity_type = KEYWORD_TYPE_DCT[key]
        ac_table = ACTIVITY_MODEL[activity_type]
        logic = ORDER_LOGIC[activity_type]
        ac = ac_table.query.filter(ac_table.term == term).one()
        applyer = WinOrderApplyer(term, ac.number, logic, activity_type)
        applyer.apply()

    def handle(self, key, **kwargs):
        activity_type = KEYWORD_TYPE_DCT[key]
        order_table = ORDER_MODEL[activity_type]
        items = order_table.query.filter(
            order_table.created_at > '2018-04-19 16:00:00').filter(
            order_table.track_id is not None).all()
        for item in items:
            if len(item.term) == 10:
                print item.term, item.id
                item.term = item.term[:-2] + item.term[-2:].zfill(3)
                item.save()
                self.apply(key, item.term)
                print 'fix, term:%s' % item.term
